<template>
  <div>
    <a-modal :width="'80vw'" :title='null' :visible='detailDate.visible' :confirm-loading='false'
      :dialog-style="{ top: '20px' }" @ok='confirms' @cancel='cancel'>
      <a-tabs v-model:activeKey='activeKey'>
        <a-tab-pane key='1' tab='待选'>
          <slot name='head'>
            <div style='display: flex;justify-content: flex-end;margin-bottom: 10px'>
              <a-button @click='searchReset'>重置</a-button>
            </div>
          </slot>
          <div class='box'>
            <div class='left' style='width: 100%'>
              <a-table size='middle' :rowKey='detailDate.valueKey' :columns='detailDate.columns'
                :dataSource='dataSource' :rowSelection='rowSelection' :pagination='ipagination'
                @change='handleTableChange' :loading='loading' class='j-table-force-nowrap components-table-demo-nested'
                :key='index' :scroll="{ x: scrollX(), y: 'calc(60vh)' }">
                <a-icon slot='searchIcon' type='search' />
                <a-icon slot='dateIcon' slot-scope='filtered' type='filter' />
                <div style='display: flex; padding: 8px' slot='updateBy' slot-scope='{ column }'>
                  <template>
                    <j-select-user-by-dep v-model='queryParam[`${column.searchIndex}`]'
                      @changeRow="(a, b, c) => onChangeUser(b || {}, 'updateBy')">
                    </j-select-user-by-dep>
                  </template>
                </div>
                <div style='display: flex; padding: 8px' slot='createBy' slot-scope='{ column }'>
                  <template>
                    <j-select-user-by-dep v-model='queryParam[`${column.searchIndex}`]'
                      @changeRow="(a, b, c) => onChangeUser(b || {}, 'createBy')">
                    </j-select-user-by-dep>
                  </template>
                </div>
                <div slot='orderStatusList' style='display: flex; flex-direction: column' slot-scope='text, record'>
                  <div style='padding: 0 10px' v-for='(item, index) in record.produceOrderTaskVo' :key='index'>
                    <div>
                      <span>{{ item.processesName || '-' }}</span>
                      <span style='margin-left: 8px'>{{
                        ((item.qualifiedNum / item.planProduceNum) * 100).toFixed(0) + '%'
                      }}</span>
                      <div style='display: flex'>
                        <a-progress style='width: 80px; margin-right: 10px'
                          :percent='(item.qualifiedNum / item.planProduceNum) * 100' :strokeWidth='5' :showInfo='false'
                          :strokeColor='checkStatus((item.qualifiedNum / item.planProduceNum) * 100)' />
                        <div style='text-align: center'>{{ item.qualifiedNum || 0 }}/{{ item.planProduceNum }}</div>
                      </div>
                    </div>
                  </div>
                </div>

                <div v-for='(item, i) in filterDropdownList' :key='i' style='display: flex; padding: 8px'
                  :slot='item.scopedSlots.filterDropdown' slot-scope='{ column }'>
                  <template>
                    <a-input v-if="item.scopedSlots.filterDropdown === 'selectProcess'" @click='openIt'
                      v-model="queryParam[column.searchIndex + 'Text']" placeholder='请选择' :read-only='true'>
                      <a-icon slot='suffix' type='down' style='color: #cdcdcd; font-size: 12px' class='down-icon' />
                      <a-icon slot='suffix' type='close-circle' theme='filled' class='close-icon'
                        @click="getSelectValue(false, '', [])" />
                    </a-input>
                    <j-select-user-by-dep v-if="item.scopedSlots.filterDropdown === 'selectPeople1'"
                      v-model='queryParam[`${item.searchIndex}`]' :multi='item.multi'
                      @changeRow='(a, b, c) => onChangeUser(b || {}, item.searchIndex)'></j-select-user-by-dep>
                    <j-select-user-by-dep v-if="item.scopedSlots.filterDropdown === 'selectPeople2'"
                      v-model='queryParam[`${item.searchIndex}`]' :multi='item.multi'
                      @changeRow='(a, b, c) => onChangeUser(b || {}, item.searchIndex)'></j-select-user-by-dep>
                    <a-input v-if="item.scopedSlots.filterDropdown === 'searchDropdown'"
                      :placeholder="'请输入'[column.title]" allowClear v-model='queryParam[column.searchIndex]'
                      style='width: 188px' />
                    <a-range-picker v-if="item.scopedSlots.filterDropdown === 'dateRangePicker'"
                      date-format='YYYY-MM-DD' valueFormat='YYYY-MM-DD' :placeholder="['开始时间', '结束时间']"
                      v-model='queryParam[`${column.searchIndex}`]' style='width: 100%' />
                    <a-select :mode="column.multi ? 'multiple' : 'default'"
                      v-if="item.scopedSlots.filterDropdown === 'selectDropdown'" :placeholder="'请选择'[column.title]"
                      allowClear style='width: 188px' v-model='queryParam[`${column.searchIndex}`]'
                      @change='(a) => changeSelect(a, column.searchIndex)' :labelInValue='false'>
                      <a-select-option v-for='(items, i) in column.options' :key='items.key' :value='items.key'>{{
                        items.label }}
                      </a-select-option>
                    </a-select>
                    <a-button v-if="item.scopedSlots.filterDropdown !== 'tooltip'" type='primary'
                      style='width: 80px; margin-left: 20px' @click='searchQuery'>
                      搜索
                    </a-button>
                  </template>
                </div>
              </a-table>
              <!-- 选择表格条数 -->
              <div class='tableSelect' v-if='dataSource.length > 0'>
                <a-checkbox v-if="detailDate.multi == 'checkbox'"
                  :checked='selectedRowKeys.length === ipagination.total ? true : false'
                  @change='selectAll'></a-checkbox>
                <span style='margin: 0 20px'>{{ `已选 ${selectionRows.length}/${ipagination.total} 项` }}</span>
                <a v-if="detailDate.multi == 'checkbox'" style='margin-right: 20px' @click='onClearSelected'>清空</a>
              </div>
            </div>
          </div>
        </a-tab-pane>
        <a-tab-pane key='2'>
          <div slot='tab' class='tabclass'>
            已选
            <span class='tabNum' v-if='selectionRows && selectionRows.length != 0'>{{ selectionRows.length }}</span>
          </div>
          <a-table size='middle' :columns='detailDate.selectedColoums' :dataSource='selectionRows'
            @change='handleLocaleChange' :loading='loading' :pagination='false' :key='index'
            :scroll="{ x: scrollX(), y: 'calc(60vh)' }">
            <span slot='action' slot-scope='text, record'>
              <a @click='delitem(record[detailDate.valueKey])'>删除</a>
            </span>
            <div slot='orderStatusList' style='display: flex; flex-direction: column' slot-scope='text, record'>
              <div style='padding: 0 10px' v-for='(item, index) in record.produceOrderTaskVo' :key='index'>
                <div>
                  <span>{{ item.processesName || '-' }}</span>
                  <span style='margin-left: 8px'>{{
                    ((item.qualifiedNum / item.planProduceNum) * 100).toFixed(0) + '%'
                  }}</span>
                  <div style='display: flex'>
                    <a-progress style='width: 80px; margin-right: 10px'
                      :percent='(item.qualifiedNum / item.planProduceNum) * 100' :strokeWidth='5' :showInfo='false'
                      :strokeColor='checkStatus((item.qualifiedNum / item.planProduceNum) * 100)' />
                    <div style='text-align: center'>{{ item.qualifiedNum || 0 }}/{{ item.planProduceNum }}</div>
                  </div>
                </div>
              </div>
            </div>
          </a-table>
        </a-tab-pane>
      </a-tabs>
    </a-modal>
  </div>
</template>
<script>
import { postAction, getAction } from '@/api/manage'
import { camelCase2UnderLine, stringToObject } from '@/utils/util'

export default {
  data() {
    return {
      activeKey: '1',
      /* table加载状态 */
      loading: false,
      /* table选中keys*/
      selectedRowKeys: [],
      /* table选中records*/
      selectionRows: [],
      detailDate: { visible: false, columns: [] },
      /* 分页参数 */
      ipagination: {
        current: 1,
        pageSize: 10,
        pageSizeOptions: ['10', '20', '30', '40'],
        showTotal: (total, range) => {
          return range[0] + '-' + range[1] + ' 共' + total + '条'
        },
        showQuickJumper: true,
        showSizeChanger: true,
        total: 0
      },
      /* 排序参数 */
      isorter: {
        sortColumn: 'create_time',
        sortType: 'desc'
      },
      // 搜索数据
      queryParam: {},
      index: 0,
      dataSource: [],
      tableData: [] //列表全部数据
    }
  },
  components: {},
  computed: {
    filterDropdownList() {
      return this.detailDate.columns.filter((e) => {
        return e.scopedSlots && e.scopedSlots.filterDropdown
      })
    },
    rowSelection() {
      return {
        onChange: (selectedRowKeys, selectedRows) => {
          this.selectedRowKeys = Array.from(new Set(selectedRowKeys))
          // this.selectionRows = selectedRows
          let arr = []
          for (let i = 0; i < this.selectedRowKeys.length; i++) {
            arr.push(
              this.tableData.find((e) => {
                return e[this.detailDate.valueKey] === this.selectedRowKeys[i]
              })
            )
          }
          this.selectionRows = arr

          let paramsS = {
            pageNo: 1,
            pageSize: this.selectedRowKeys.length,
            id: this.selectedRowKeys.join()
          }
          this.getSelectRows(paramsS)
        },
        getCheckboxProps: (record) => ({
          props: {
            defaultChecked: this.selectedRowKeys.indexOf(record[this.detailDate.valueKey]) > -1 ? true : false
          }
        }),
        type: this.detailDate.multi ? 'checkbox' : 'radio',
        columnTitle: ' ',
        preserveSelectedRowKeys: true,
        selectedRowKeys: this.selectedRowKeys
      }
    }
  },
  watch: {},
  created() {
  },
  mounted() {
  },
  methods: {
    checkStatus(value) {
      if (value == 0) {
        return '#DFDFDF'
      } else if (value >= 100) {
        return '#52c41a'
      } else {
        return '#1890ff'
      }
    },
    onChangeUser() {
      this.searchQuery()
    },
    // 初始化
    getInit(v) {
      console.log(v, 'vvvvvv231')

      this.detailDate = v
      this.detailDate.selectedColoums = [...this.detailDate.columns]
      this.detailDate.selectedColoums.push({
        title: '操作',
        width: 120,
        scopedSlots: { customRender: 'action' }
      })
      // 获取勾选的默认值
      if (v.value) {
        this.selectedRowKeys = v.value.split(',')
        let paramsS = {
          pageNo: 1,
          pageSize: this.selectedRowKeys.length,
          id: this.detailDate.value
        }
        this.getSelectRows(paramsS)
      } else {
        this.selectedRowKeys = []
        this.selectionRows = []
      }
      this.index += 1
      this.loadData(1)
    },
    getSelectRows(params) {
      let getDataAction = this.detailDate.action == 'post' ? postAction : getAction
      getDataAction(this.detailDate.list, params)
        .then((res) => {
          if (res.success) {
            this.selectionRows = res.result.records || res.result
          } else {
            this.$antdMessage.warning(res.message)
          }
        })
        .finally(() => {
          this.loading = false
        })
    },
    // 获取表格数据
    loadData(arg) {
      if (!this.detailDate.list) {
        this.$antdMessage.error('请设置list属性!')
        return
      }
      //加载数据 若传入参数1则加载第一页的内容
      if (arg === 1) {
        this.ipagination.current = 1
      }
      let par = {
        pageNo: this.ipagination.current,
        pageSize: this.ipagination.pageSize,
        ...this.isorter
      }
      // console.log(this.queryParam)
      var params = { ...par, ...this.queryParam }

      if (params.serialPropertiesCode) {
        params.serialPropertiesCode = params.serialPropertiesCode.join(',')
      }

      if (params.createTime && params.createTime.length) {
        params.createTimeBegin = params.createTime[0] + ' 00:00:00'
        params.createTimeEnd = params.createTime[1] + ' 23:59:59'
        delete params.createTime
      } else {
        delete params.createTime
      }

      if (params.updateTime && params.updateTime.length) {
        params.updateTimeBegin = params.updateTime[0] + ' 00:00:00'
        params.updateTimeEnd = params.updateTime[1] + ' 23:59:59'
        delete params.updateTime
      } else {
        delete params.updateTime
      }


      let dealPar = stringToObject(JSON.parse(JSON.stringify(params)))
      this.loading = true
      let getDataAction = this.detailDate.action == 'post' ? postAction : getAction
      getDataAction(this.detailDate.list, dealPar)
        .then((res) => {
          if (res.success) {
            //update-begin---author:zhangyafei    Date:20201118  for：适配不分页的数据列表------------
            this.dataSource = res.result.records || res.result
            this.tableData = [...this.tableData, ...this.dataSource]
            const removeDuplicateObj = (arr) => {
              let obj = {}
              arr = arr.reduce((newArr, next) => {
                obj[next[this.detailDate.valueKey]]
                  ? ''
                  : (obj[next[this.detailDate.valueKey]] = true && newArr.push(next))
                return newArr
              }, [])
              return arr
            }
            this.tableData = removeDuplicateObj(this.tableData)
            if (res.result.total) {
              this.ipagination.total = res.result.total
            } else {
              this.ipagination.total = res.result.length || 0
            }
            //update-end---author:zhangyafei    Date:20201118  for：适配不分页的数据列表------------
          } else {
            this.$antdMessage.warning(res.message)
          }
        })
        .finally(() => {
          this.loading = false
        })
    },
    // 全选的方法
    selectAll() {
      if (this.ipagination.total === this.selectionRows.length) {
        this.onClearSelected()
        this.index += 1
      } else {
        let selectedRowKeys = this.dataSource.map((e) => {
          return e[this.detailDate.valueKey]
        })
        this.selectedRowKeys = Array.from(new Set([...this.selectedRowKeys, ...selectedRowKeys]))
        let arr = []
        for (let i = 0; i < this.selectedRowKeys.length; i++) {
          arr.push(
            this.tableData.find((e) => {
              return e[this.detailDate.valueKey] === this.selectedRowKeys[i]
            })
          )
        }
        this.selectionRows = arr
        this.index += 1
      }
    },
    // 清空
    onClearSelected() {
      this.selectedRowKeys = []
      this.selectionRows = []
      this.index += 1
    },
    // 页码切换
    handleTableChange(pagination, filters, sorter) {
      if (Object.keys(sorter).length > 0) {
        this.isorter.sortColumn = camelCase2UnderLine(sorter.field)
        this.isorter.sortType = 'ascend' == sorter.order ? 'asc' : 'desc'
      }
      this.ipagination = pagination
      this.loadData()
    },
    handleLocaleChange(pagination, filters, sorter) {
      const { order, field } = sorter
      const dateField = field === "createTime" ? "createTime" : field === "updateTime" ? "updateTime" : null
      if (dateField) {
        this.selectionRows = this.selectionRows.sort((a, b) => {
          const dateA = new Date(a[dateField])
          const dateB = new Date(b[dateField])
          return order === "ascend" ? dateA - dateB : dateB - dateA
        })
      }
    },
    // 搜索
    searchQuery() {
      this.loadData(1)
    },
    // 重置
    searchReset() {
      this.queryParam = {}
      this.loadData(1)
    },
    // 删除
    delitem(v) {
      this.selectedRowKeys = this.selectedRowKeys.filter((e) => e !== v)
      this.selectionRows = this.selectionRows.filter((e) => e[this.detailDate.valueKey] !== v)
      this.index += 1
    },
    scrollX() {
      let xnum = 0
      for (let item of this.detailDate.columns) {
        xnum += Number(item.width) || 0
      }
      return xnum
    },
    // 确定
    confirms() {
      this.cancel()
      console.log(this.selectionRows, ' this.selectionRows')
      // return
      let text = this.selectionRows.map((e) => {
        return e[this.detailDate.textKey]
      })
      this.$emit('getSelectValue', this.selectedRowKeys.toString(), text.toString(), this.selectionRows)
    },
    // 关闭
    cancel() {
      this.detailDate.visible = false
      this.activeKey = '1'
      this.$emit('cancel')
    }
  }
}
</script>

<style scoped>
.box {
  display: flex;
  justify-content: start;
}

.left {
  width: 75%;
  position: relative;
}

.right {
  margin-left: 2%;
  width: 23%;
}

.tableSelect {
  position: absolute;
  left: 22px;
  bottom: 13px;
  color: #000;
  z-index: 99;
}

.selList {
  height: 500px;
  overflow-y: scroll;
}

.tabclass {
  position: relative;
  /* border: 1px solid red; */
}

.tabNum {
  position: absolute;
  top: -13px;
  right: -13px;
  min-width: 22px;
  height: 22px;
  background: #f25643;
  /* padding: 2px; */
  border-radius: 50%;
  display: inline-block;
  text-align: center;

  font-size: 14px;
  font-family: Microsoft YaHei;
  font-weight: 400;
  color: #ffffff;
  line-height: 22px;
}
</style>
